/**
 * 联动选择框组件
 */
layui.define(['component', 'layer', 'form', 'methods'], function (exports) {
    var options = {},
        methods = layui.methods,
        form = layui.form,
        o = layui.jquery;

    const build = {
        inspect: () => {
            const miss = ['url', 'deep', 'label', 'map'];
            const missMap = ['title', 'name'];
            miss.map((v) => {
                if (!options.hasOwnProperty(v) || !options.url) {
                    throw "未给定参数：" + v;
                }
            })

            missMap.map((v) => {
                if (!options.map.hasOwnProperty(v) || !options.url) {
                    throw "未给定参数：map." + v;
                }
            })

            if (options.map.title.length < options.deep) {
                throw "标题个数错误" ;
            }

            if (options.map.name.length < options.deep) {
                throw "name个数错误" ;
            }
        },
        option: (index = 0, pid = 0, active = '') => {
            var key = options.map.key ? options.map.key : 'title', value = options.map.value ? options.map.value : 'id';
            methods.fetchGet(options.url, {id: pid}, (res) => {
                var html = `<option value="">请选择${options.map.title[index]}</option>`;
                res.data.map((v) => {
                    const selected = active == v[value] ? 'selected' : '';
                    html += `<option value="${v[value]}" ${selected}>${v[key]}</option>`;
                })
                o(options.elem).find(`select[data-index="${index}"]`).html(html);
                form.render();
            }, false);
        },

        core: () => {
            const select = () => {
                var html = '';
                for (let i = 0; i < options.deep; i++) {
                    html += `
                    <div class="layui-input-inline">
                        <select name="${options.map.name[i]}" lay-filter="${options.map.name[i]}" data-index="${i}" disabled lay-search>
                            <option value="">请选择${options.map.title[i]}</option>
                        </select>
                    </div>
                    `
                }
                return html;
            }
            return `
                <div class="layui-col-xs12 layui-col-sm12 layui-col-md12">
                    <div class="layui-form-item">
                        <label class="layui-form-label">${options.label}</label>
                        ${select()}
                    </div>
                </div>
            `;
        },
        value: () => {
            if (options.map.hasOwnProperty('active') && options.map.active.length > 0) {
                options.map.name.map((v, i) => {
                    if (!i) {
                        build.option(i, 0, options.map.active[i]);
                    } else {
                        build.option(i, options.map.active[i - 1], options.map.active[i]);
                    }
                });
            } else {
                build.option();
            }
        },
        listener: () => {
            options.map.name.map((v, i) => {
                if (i < options.deep - 1) {
                    form.on(`select(${v})`, function (data) {
                        var value = data.value, index = parseInt(o(data.elem).attr('data-index'));
                        //置空后续select
                        for (let i = index + 1; i <= options.deep; i++) {
                            o(options.elem).find('select').eq(i).html(`<option value="">请选择${options.map.title[i]}</option>`);
                        }
                        data.value ? build.option(index + 1, value) : form.render();
                    });
                }
            })
        }
    }


    var component = layui.component({
        name: 'linkage',
        config: {
            elem: '.layui-linkage',
        },
        render: function () {
            var that = this, html = ''
            options = that.config;
            try {
                build.inspect()

                //构建核心select
                html += build.core();

                //构建HTML
                options.elem.html(html);

                //加载option
                build.value();

                //监听
                build.listener();

                //渲染表单
                form.render('select');

                //解锁
                setTimeout(() => {

                    o(options.elem).find(`select`).removeAttr('disabled');

                }, 500);
            } catch (e) {
                console.error(e);
            }
        },
    });

    exports(component.CONST.MOD_NAME, component);
});
